// pages/applydesc/applydesc.js

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowGetUserInfo: false
  },

  //授权获取个人头像和昵称
  getUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        'isShowGetUserInfo': false
      })
      wx.setStorageSync('wx_head', e.detail.userInfo.avatarUrl);
      wx.setStorageSync('wx_name', e.detail.userInfo.nickName);
      wx.login({
        success: res => {
          wx.setStorageSync('code', res.code);
          this.parseUnionID(e.detail.encryptedData, e.detail.iv);
        }
      })
      wx.showToast({
        title: '获取个人信息成功',
        icon: 'none'
      });
    } else {
      wx.showToast({
        title: '个人信息授权失败',
        icon: 'none'
      });
      wx.redirectTo({
        url: '/pages/welcome/applydesc/applydesc'
      });
    }
  },

  /**
   * 解析unionID
   */
  parseUnionID(encryptedData, iv) {
    wx.showLoading({
      title: '拼命加载中...',
    });
    wx.request({
      url: app.globalData.url + 'c=home&m=getPhoneNumber',
      data: {
        'encryptedData': encryptedData,
        'iv': iv,
        'code': wx.getStorageSync('code')
      },
      success: (res) => {
        wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          //保存unionID到本地
          // var phone = res.data.purePhoneNumber;
          var union_id = res.data.unionId;
          wx.setStorageSync('union_id', union_id);
          this.isRegister(union_id);
        } else {
          wx.showToast({
            title: '获取unionID失败，请重试',
            icon: 'none'
          })
          this.setData({
            getPhoneNumberChange: true
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (JSON.stringify(options) !== '{}') {
      app.globalData.enterpriseId = options.enterpriseId;
      app.globalData.refId = options.refId;
      app.globalData.idNumber = options.idNumber;
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      let arrPara = scene.split("&")
      let arr = [];
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split("=");
        if (arr[0] == 'enterpriseId') {
          app.globalData.enterpriseId = arr[1];
        }
        if (arr[0] == 'refId') {
          app.globalData.refId = arr[1];
        }
        if (arr[0] == 'idNumber') {
          app.globalData.idNumber = arr[1];
        }
      }
    }
    var user_id = wx.getStorageSync('user_id');
    if (user_id) {
      wx.showLoading({
        title: '拼命加载中...',
        icon: 'none'
      });
      wx.request({
        url: app.globalData.url + 'c=user&m=getUserInfo&user_id=' + user_id,
        success: res => {
          wx.hideLoading();
          res = res.data;
          if (res.status == 200) {
            if (res.data.id && res.data.id == user_id) {
              // wx.showModal({
              //   title: '提示',
              //   content: '当前微信号已注册',
              //   showCancel: false
              // });
              wx.showToast({
                title: '当前微信号已注册',
                icon: 'none'
              })
              // 需改调整地址
              wx.redirectTo({
                url: '/pages/student/personal/personal'
              });
              // wx.redirectTo({
              //   url: '/pages/guidanceStudy/index/index'
              // });
            } else {
              //未注册
              this.getSetting();
            }
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            });
          }
        }
      });
    } else {
      this.getSetting();
    }
  },

  //授权
  getSetting() {
    wx.getSetting({
      success: res => {
        //没授权过
        if (!res.authSetting['scope.userInfo']) {
          this.setData({
            isShowGetUserInfo: true
          })
        } else {
          //授权过
          if (!(wx.getStorageSync('wx_name') && wx.getStorageSync('wx_head'))) {
            wx.getUserInfo({
              success: res => {
                wx.setStorageSync('wx_name', res.userInfo.nickName);
                wx.setStorageSync('wx_head', res.userInfo.avatarUrl);
              }
            });
          }
        }
      }
    })
  },

  //判断unionID是否注册
  isRegister(union_id) {
    wx.request({
      url: app.globalData.url + 'c=user&m=isRegister',
      data: {
        union_id: union_id
      },
      success: res => {
        // wx.hideLoading();
        res = res.data;
        if (res.status == 200) {
          if (res.data.is_register != 0) {
            //已注册
            wx.setStorageSync('user_id', res.data.user_id);
            app.globalData.userId = res.data.user_id;
            // 需改调整地址
            wx.redirectTo({
              url: 'pages/student/personal/personal'
            });
            // wx.redirectTo({
            //   url: '/pages/guidanceStudy/index/index'
            // });
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
      }
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})